#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>

#define u8  unsigned char
#define u32 unsigned int

typedef struct frame_info {
	u8 dlc:      4,   /* data length code */
     dontcare: 2,   /* don't care */
     rtr:      1,   /* remote transmission request */
     format:   1;   /* frame format 0:SFF 1:EFF */
} frame_info_t;

typedef struct
{
	u32 id;                  /* identifier */
  frame_info_t frm_info;   /* frame information */
  u8 data[8];              /* data */
  u8 padding[3];           /* padding bytes */
} CAN_PACKAGE;

int main(void)
{
	int fd, i;
	CAN_PACKAGE wpkg, rpkg;
	
	fd = open("/dev/can0", O_RDWR);
	if(fd < 0) {
		printf("Can not open CAN bus device\n");
		exit(1);
	}
	
	wpkg.id = 0xb130;
	wpkg.frm_info.dlc = 8;
	wpkg.frm_info.rtr = 0;
	wpkg.frm_info.format = 1;
	wpkg.data[0] = 0xa0;
  wpkg.data[1] = 0xa1;
  wpkg.data[2] = 0xa2;
  wpkg.data[3] = 0xa3;
  wpkg.data[4] = 0xa4;
  wpkg.data[5] = 0xa5;
  wpkg.data[6] = 0xa6;
  wpkg.data[7] = 0xa7;
	printf("Writing packet to CAN bus\n");
	write(fd, &wpkg, sizeof(wpkg));
	printf("Reading packet from CAN bus\n");
	while(read(fd, &rpkg, sizeof(rpkg))) {
		printf("Packet ID: %x\n", rpkg.id);
		printf("Packet data: [ ");
		for(i = 0; i < rpkg.frm_info.dlc; i++)
			printf("%x ", rpkg.data[i]);
		printf("]\n");
	}
	close(fd);
	return 0;
}
